package com.pay.strategy.impl;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.pay.common.pay.constant.Constant;
import com.pay.config.AlipayConfig;
import com.pay.entity.PaymentChannelDO;
import com.pay.entity.PaymentInfoDO;
import com.pay.service.open.api.OpenPaymentCoreService;
import com.pay.strategy.PayStrategy;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * @author 周益和
 * @ClassName AliPayStrategy
 * @qq 1552951165
 */
@Component
@Slf4j
public class AliPayStrategy implements PayStrategy {
     //获得初始化的AlipayClient
     private AlipayClient alipayClient = new DefaultAlipayClient(
            AlipayConfig.gatewayUrl, AlipayConfig.app_id,
            AlipayConfig.merchant_private_key, "json",
            AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
    
    @Autowired
    private OpenPaymentCoreService openPaymentCoreService;
    
    @SneakyThrows
    @Override
    public String toPay(PaymentInfoDO paymentInfoDO, PaymentChannelDO paymentChannelDo) {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(
                AlipayConfig.gatewayUrl, AlipayConfig.app_id,
                AlipayConfig.merchant_private_key, "json",
                AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(paymentChannelDo.getSyncUrl());
        alipayRequest.setNotifyUrl(paymentChannelDo.getAsynUrl());
        
        //        //商户订单号，商户网站订单系统中唯一订单号，必填
        //        String out_trade_no =paymentInfoDO.getOrderId();
        //        //付款金额，必填
        //        String total_amount = request.getParameter("WIDtotal_amount");
        //        //订单名称，必填
        //        String subject = request.getParameter("WIDsubject");
        //        //商品描述，可空
        //        String body = request.getParameter("WIDbody");
        
        alipayRequest.setBizContent("{\"out_trade_no\":\"" +
                paymentInfoDO.getOrderId() + "\","
                + "\"total_amount\":\"" + paymentInfoDO.getPayAmount().toString() + "\","
                + "\"subject\":\"" + paymentInfoDO.getOrderName() + "\","
                + "\"body\":\"" + paymentInfoDO.getOrderBody() + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        
        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节
        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        return result;
    }
    
    @Override
    public boolean payIdByPayResult(PaymentInfoDO paymentInfo) {
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();
        // 商户订单id
        model.setOutTradeNo(paymentInfo.getOrderId());
        // 第三方支付返回id
        model.setTradeNo(paymentInfo.getPartyPayId());
        // 调用支付宝接口传递两个id 商户订单id、第三方支付返回id？
        alipayRequest.setBizModel(model);
        try {
            // 根据支付宝支付id或者订单号码主动查询
            AlipayTradeQueryResponse alipayResponse = alipayClient.execute(alipayRequest);
            log.info("alipayResponse:{}", alipayResponse);
            
            // 1.先判断 返回结果是否是为10000
            if (!Constant.ALI_PAY_QUERY_RESPONSE_CODE.equals(
                    alipayResponse.getCode()
            )) {
                return Boolean.FALSE;
            }
            
            // 2.判断支付状态 是否已经支付
            if (!Constant.ALI_PAY_TRADESTATUS_SUCCESS.equals(
                    alipayResponse.getTradeStatus()
            )) {
                return Boolean.FALSE;
            }
            
            // 3.判断用户实际支付金额 与下单金额是否一致
            if (!paymentInfo.getPayAmount().equals(
                    new BigDecimal(alipayResponse.getTotalAmount())
            )) {
                // 存的 用户支付 1000元  用户实际支付了1元钱
                // 该订单设定异常
                return Boolean.FALSE;
            }
            
            // 4.将用户实际支付的状态 同步到表中
            paymentInfo.setPartyPayId(alipayResponse.getTradeNo());
            int result = openPaymentCoreService.updatePaymentStatusOk(paymentInfo);
            return result > Constant.DEFAULT_VALUE_ZERO;
        } catch (Exception e) {
            log.error("e:{}", e);
            return Boolean.FALSE;
        }
    }
}

